package com.xusheng.msmservice.utils;

import com.xusheng.msmservice.service.impl.MsmServiceImpl;


import java.util.Scanner;

/*public class test2 {
    public static void main(String[] args) {
        MsmServiceImpl msmService = new MsmServiceImpl();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入手机号:");
        String phone = scanner.next();
        String verCode = msmService.send(phone);
        if (verCode!=""){
            System.out.println("短信发送成功");
        }
        else {
            System.out.println("短信发送失败");
        }

    }
}*/
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

   public class test2 {

    public static void main(String[] args) throws IOException {
        String url = "https://smssend.shumaidata.com/sms/send";
        String appCode = "521e541f888249318983eb49952aac75";

        Map<String, String> params = new HashMap<>();
        params.put("receive", "188****1212");
        params.put("tag", "2345");
        params.put("templateId", "MD8B7116BC");

        String result = postForm(appCode, url, params);
        System.out.println(result);
    }
    /**
     * 用到的HTTP工具包：okhttp 3.13.1
     * <dependency>
     * <groupId>com.squareup.okhttp3</groupId>
     * <artifactId>okhttp</artifactId>
     * <version>3.13.1</version>
     * </dependency>
     */
    public static String postForm(String appCode, String url, Map<String, String> params) throws IOException {
        url = url + buildRequestUrl(params);
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        Response response = client.newCall(request).execute();
        System.out.println("返回状态码" + response.code() + ",message:" + response.message());
        String result = response.body().string();
        return result;
    }

    public static String buildRequestUrl(Map<String, String> params) {
        StringBuilder url = new StringBuilder("?");
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            url.append(key).append("=").append(params.get(key)).append("&");
        }
        return url.toString().substring(0, url.length() - 1);
    }
}